package com.lishem.networknio.niorect;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class NIOReactorServer {

    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open(); // 获得NIO服务端
        ssc.configureBlocking(false); // 设置非阻塞
        // 配置Boss这个Selector
        Selector boss = Selector.open();
        SelectionKey bossKey = ssc.register(boss, 0, null);
        bossKey.interestOps(SelectionKey.OP_ACCEPT); // boss只关注accept事件

        // 服务端绑定8080 端口
        ssc.bind(new InetSocketAddress(8080));

        // 1. 创建worker并初始化
        Worker[] workers = new Worker[2];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("worker-" + i);
        }

        AtomicInteger index = new AtomicInteger();
        while (true) {
            boss.select();
            Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                iter.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.debug("connected...{}", sc.getRemoteAddress());
                    // 2. 建立链接 关联selector 读写操作交给worker线程去做
                    log.debug("before register...{}", sc.getRemoteAddress());

                    /**
                     * 这个Register一定要先于sc.register执行
                     * 因为一旦阻塞住，新注册的SocketChannel不会被监听
                     */
                    workers[index.getAndIncrement() % workers.length].register(sc);
                    log.debug("after register...{}", sc.getRemoteAddress());
                }
            }
        }
    }

    /**
     * 处理读写事件
     */
    static class Worker implements Runnable {
        private Thread thread; // worker所属线程
        private Selector selector; // worker持有selector
        private String name; // worker名字
        private volatile boolean start = false; //还未初始化
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

        public Worker(String name) {
            this.name = name;
        }

        /**
         * 初始化线程和selector
         */
        public void register(SocketChannel sc) throws IOException {
            // start变量标记此段代码只执行一次
            if (!start) {
                thread = new Thread(this, this.name);
                selector = Selector.open();
                thread.start();
                start = true;
            }
            // 向队列添加任务，但这个任务并没有立刻执行
            queue.add(() -> {
                try {
                    sc.register(selector, SelectionKey.OP_READ, null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            selector.wakeup(); // 唤醒selector 添加完任务，告诉selector 该干活了！
        }

        @Override
        public void run() {
            while (true) {
                try {
                    selector.select(); // 阻塞等事件
                    Runnable task = queue.poll();
                    if (task != null) {
                        task.run(); // 在这里执行了真正的注册
                    }
                    // 如果有事件发生，阻塞被唤醒，拿到所有事件并遍历
                    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                    while (iter.hasNext()) {
                        SelectionKey key = iter.next();
                        iter.remove();
                        // 可读
                        if (key.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) key.channel();
                            log.debug("read....{}", channel.getRemoteAddress());
                            channel.read(buffer);
                            buffer.flip();
                            System.out.println("打印BUFFER");
                            // 打印buffer
                        } else if (key.isWritable()) {
                            // 省略
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}